package com.jasperframework.boot.common.utils;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


/**
  * <p>  </p>
  *
  * @site https://miliqkdoc.motopa.cn/
  * @author daizhao
  * @date 2022/12/12 12:12
  */
public class UploadUtils {

	private static final Logger logger = LoggerFactory.getLogger(UploadUtils.class);

	/**
	 * 上传文件(将文件名加毫秒数)
	 * @param path		文件路径
	 * @param upload	封装文件类
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public static String uploadFile(String path, MultipartFile upload) throws IllegalStateException, IOException {
		String fileName = getRandomFilename(upload.getOriginalFilename());
		File targetPath = new File(path);
		if (!targetPath.exists()) {
			targetPath.mkdirs();
		}
		File targetFile = new File(path+"/"+fileName);
		// 保存
		upload.transferTo(targetFile);
		return fileName;
	}

	/**
	 * 上传文件(原始文件，不改变文件名称)
	 * @param path		文件路径
	 * @param upload	封装文件类
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public static File uploadOriginFile(String path, MultipartFile upload) throws IllegalStateException, IOException {
		String fileName = upload.getOriginalFilename();
		File targetPath = new File(path);
		if (!targetPath.exists()) {
			targetPath.mkdirs();
		}
		File targetFile = new File(path+"/"+fileName);
		if (!targetFile.exists()) {
			// 保存   存在的文件不许再次上传
			upload.transferTo(targetFile);
		}else{
			File newTargetFile = renameTo(targetFile,0);
			upload.transferTo(newTargetFile);
			return newTargetFile;
		}
		return targetFile;
	}

	public static File renameTo(File targetFile, int i){
		 if(!targetFile.exists())
		      return targetFile;
		  else{
			  i++;
			  String fileName = targetFile.getName().split("\\.")[0];
			  String suffix = targetFile.getName().split("\\.")[1];
			  if(i == 1){
				  String newFileName = fileName.concat("(" + i + ")").concat(".").concat(suffix);
				  return renameTo(new File(targetFile.getParentFile()+"/"+newFileName), i);
			  }else{
				  String newFileName = fileName.replaceAll("\\(\\d+\\)", "(" + i + ")").concat(".").concat(suffix);
				  return renameTo(new File(targetFile.getParentFile()+"/"+newFileName), i);
			  }
		  }

	}

	/**
	 * 将字符串转为长整型
	 * @param o 原始字符串
	 * @return
	 */
	public static int toInt(String o) {
		try {
			return Integer.parseInt(o);
		} catch (Exception e) {
			return 0;
		}
	}

	// 时间戳加9位随机码
	public static String getRandomFilename(String filename) {
		String randomCode = null;
		try {
			randomCode += RandomStringUtils.random(5, "0123456789");
			randomCode += RandomStringUtils.random(5, "abcdefghijklmnopqrstuvwxyz-");
			randomCode += RandomStringUtils.random(5, "ABCDEFGHIJKLMNOPQRSTUVWXYZ_");

			randomCode = RandomStringUtils.random(9, randomCode);
			if (filename.contains(".")) {
				String ext = filename.substring(filename.lastIndexOf("."));
				return randomCode + System.currentTimeMillis() + ext;
			} else {
				String ext = filename;
				return randomCode + System.currentTimeMillis() + ext;
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			/* 如果生成序列号失败,则直接返回null */
			return null;
		}
	}

}
